package com.sunnyweather.android.logic.service

import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.R
import com.sunnyweather.android.SunnyWeatherApplication
import com.sunnyweather.android.logic.Repository
import com.sunnyweather.android.logic.model.Location
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.logic.util.AMapPrivacyClaim
import com.sunnyweather.android.logic.util.LogUtil
import com.sunnyweather.android.ui.weather.WeatherActivity

object AMapPositionService {
    private lateinit var locationClient:AMapLocationClient
    private lateinit var locationListener: AMapLocationListener
    private lateinit var locationClientOption:AMapLocationClientOption
    //开始后台定位
    fun start(){
        AMapPrivacyClaim.claim()
        locationClient= AMapLocationClient(SunnyWeatherApplication.context.applicationContext)
        //配置定位的详细参数
        locationClientOption=AMapLocationClientOption().apply {
            setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport)
            setInterval(60000)
            setNeedAddress(true)
        }

        //配置处理定位结果的回调函数
        locationListener= AMapLocationListener { amapLocation ->
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    val address=amapLocation.address
                    val name=amapLocation.city
                    val location=Location(amapLocation.latitude,amapLocation.longitude)
                    val code=amapLocation.adCode
                    val place= Place("localPosition",name,address,location,code)
                    LogUtil.d("AmapLocation",place.toString())

                    val mainActivity=MainActivity.runningInstance

                    val weatherActivity=WeatherActivity.runningInstance

                    //如果在MainActivity直接定位跳转
                    if(mainActivity!=null){
                        if(!Repository.isStored()){
                            Repository.setPlace(place)
                            val intent=Intent(mainActivity, WeatherActivity::class.java).apply {
                                putExtra("place_lat", place.location.lat)
                                putExtra("place_lng", place.location.lng)
                                putExtra("place_name", place.name)
                            }
                            mainActivity.startActivity(intent)
                        }
                    }


                    //在WeatherActivity的话就刷新数据
                    if(weatherActivity!=null&&mainActivity==null){
                        if(place.name!=Repository.getRestoredPlace().name){
                            Repository.setPlace(place)
                            weatherActivity.weatherViewModel.getPlaceOptions()
                            if(weatherActivity.weatherLayoutBinding.placeNavigator.selectedItemId== R.id.localPlace){
                                weatherActivity.weatherViewModel.changePlace(place)
                            }
                            weatherActivity.weatherViewModel.refreshWeather()
                            Toast.makeText(SunnyWeatherApplication.context,"定位成功", Toast.LENGTH_SHORT).show()
                        }
                    }

                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    LogUtil.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    Toast.makeText(SunnyWeatherApplication.context,"定位失败！请确认已正确授予定位权限", Toast.LENGTH_SHORT).show()


                    val failedPlace=Place("location Error","location Error","location Error",
                        Location(0.0,0.0),"location Error")


                }
            }

        }


        locationClient.setLocationListener(locationListener)
        locationClient.setLocationOption(locationClientOption)
        try{
            locationClient.startLocation()
        }catch (e:Exception){
            LogUtil.e("AmapstartLocationError",e.message.toString())
        }
        LogUtil.d("AmapLocationStart", locationClient.isStarted.toString())
    }

    //关闭后台定位
    fun stop(){
        locationClient.stopLocation()
        LogUtil.d("AmapLocationStop", locationClient.isStarted.toString())
        LogUtil.d("AmapLocation","stopClient!")
    }

    //销毁Client实例
    fun destroyClient(){
        if(locationClient!=null){
            locationClient.onDestroy()
            LogUtil.d("AmapLocation","destroyClient!")
        }
    }
}